package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"sort"

	"banmao.com/jswitch/Ijswitch"
)

// Jdk结构体 按 Version 字段排序
type byVersion []Ijswitch.Jdk

func (a byVersion) Len() int           { return len(a) }
func (a byVersion) Less(i, j int) bool { return a[i].Version < a[j].Version }
func (a byVersion) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	defer func() {
		if err := recover(); err != nil {
			fmt.Println("程序出错了:", err)
		}

		clearInputBuffer()
		tempStr := ""
		fmt.Scanf("%s", &tempStr)
	}()

	var loadPtr = flag.String("load", "", "输入扫描路径")

	flag.Parse()

	var loadStr = *loadPtr

	loadStr = "D:\\ProgramSoft\\Java"

	fmt.Println("扫描路径：" + loadStr)

	os := runtime.GOOS
	fmt.Println("当前操作系统:", os)

	var handler Ijswitch.SuperHandler

	switch os {
	case "darwin":
		fmt.Println("Mac OS")
	case "linux":
		fmt.Println("Linux")
	case "windows":
		handler = &Ijswitch.WinJswitchParam{ScanPath: loadStr}
	default:
		panic("未实现此系统方法, OS: " + os)
	}

	jdkList := handler.ScanJDK()

	sort.Sort(byVersion(jdkList))

	// fmt.Println("扫描结果：" + fmt.Sprint(jdkList))

	fmt.Printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n扫描已完成, 请选择需要的JDK版本:\n")

	for i, jdk := range jdkList {
		fmt.Printf("%d %-15s (%s) \n", i+1, jdk.Version, jdk.Path)
	}

	var jdkIndex int

	// var pass bool = false

	for {
		fmt.Printf("请输入 1-%d: ", len(jdkList))
		fmt.Scanf("%d", &jdkIndex)
		if jdkIndex > 0 && jdkIndex <= len(jdkList) {
			break
		} else {
			fmt.Println("输入的 JDK 不存在, 请重新输入")
			fmt.Scanf("%d", &jdkIndex)
		}
	}

	if err := handler.SetEnv(jdkIndex-1, &jdkList); err != nil {
		panic("设置环境变量失败" + err.Error())
	}

	fmt.Println("设置环境变量成功")

}

// 清空输入缓冲区
func clearInputBuffer() {
	cmd := exec.Command("cmd", "/c", "pause")
	cmd.Stdout = os.Stdout
	cmd.Stdin = os.Stdin
	cmd.Run()
}
